//修改支付密码弹窗

import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Row, Col, Steps, message } from 'antd';
import { getCode } from '@/services/user';
import CommonLoading from '@/components/CommonLoading';
import { verificationCode, changePayPassword, changeSellerPayPassword } from '../../service';
import CommonModal from '@/components/CommonModal';
const { Step } = Steps;

export default ({ PayModalSwitch, personageMessage, PayModalOk, PayModalNo, pageInit }) => {

    //步骤条索引
    const [current, setCurrent] = useState(0)
    const [second, setSecond] = useState(0)
    const [spinning, setSpinning] = useState(false)

    useEffect(() => {
        // dispatch({ type: 'accountSafety/getInitPage' });
        if (PayModalSwitch) {
            form.resetFields();
        }
    }, [PayModalSwitch])

    const layout = {
        labelCol: {
            span: 7,
        },
        wrapperCol: {
            span: 12,
        },
    };

    const [form] = Form.useForm();

    //获取验证码
    const code = async (phone) => {
        const res = await getCode({
            mobile: phone,
            type: 4
        })
        if (res.success) {
            message.success('验证码发送成功!');
        }
    }

    //获取验证码点击校验倒数事件
    const verification = async () => {
        let num = 59
        setSecond(59)
        let seconds = setInterval(() => {
            num = num - 1
            setSecond(num)
            if (num === 0) {
                clearInterval(seconds);
                setSecond(0);
            }
        }, 1000)
        code(personageMessage.mobile)
    }

    //下一步的点击事件
    function next() {
        form.validateFields().then(async (val) => {
            // setCurrent(1)
            setSpinning(true)
            let obj = {}
            obj.phone = personageMessage.mobile
            obj.code = val.code
            obj.type = 4
            const res = await verificationCode(obj)
            if (res.code == 200) {
                setCurrent(1)
                setSpinning(false)
            } else {
                setSpinning(false)
            }
        }).catch(() => {

        })
    }

    //确认点击事件
    function PayModalVerify() {
        form.validateFields().then(async (val) => {
            setSpinning(true)
            if (val.payPassWord !== val.payPassWordTwo) {
                return;
            }
            let obj = {}
            obj.newPwd = val.payPassWord
            obj.repeatPwd = val.payPassWordTwo
            obj.userId = JSON.parse(localStorage.getItem("zjf-erp-current-user")).id;
            obj.tenantId = '000000';
						let res;
						if(personageMessage.accountNo) {
							res = await changeSellerPayPassword(obj);
						} else {
							res = await changePayPassword(obj);
						}
            if (res.code == 200) {
                message.success('设置成功')
                setCurrent(0)
                PayModalOk()
                form.resetFields()
                setSpinning(false)
                // dispatch({ type: 'accountSafety/getInitPage' })
                pageInit()
            }
            let timer = setTimeout(() => {
                setSpinning(false);
                clearTimeout(timer);
                timer = null;
            }, 300)
        }).catch(() => {

        })
    }

    //取消弹框点击事件
    const PayModalCancel = async () => {
        form.resetFields()
        setCurrent(0)
        PayModalNo()
    }

    return (
        <CommonModal
            title="设置支付密码"
            visible={PayModalSwitch}
            onCancel={PayModalCancel}
            footer={
                current == 0 ?
                    [<Button key={1} onClick={PayModalCancel} loading={spinning}>取消</Button>, <Button key={2} type="primary" loading={spinning} onClick={next}>下一步</Button>] :
                    [<Button key={1} onClick={PayModalCancel} loading={spinning}>取消</Button>, <Button key={2} type="primary" loading={spinning} onClick={PayModalVerify}>确定</Button>]
            }
        >
            <Steps current={current}>
                <Step title="账户验证" />
                <Step title="设置支付密码" />
            </Steps>

            <div style={{ marginTop: 25 }}>
                <Form
                    {...layout}
                    name="pay"
                    form={form}
                    // hideRequiredMark={true}
                    initialValues={{
                        phoneNumber: personageMessage.mobile,
                    }}
                >
                    {current == 0 ?
                        <div>
                            <Form.Item
                                label="当前手机"
                                name="phoneNumber"
                            >
                                <Input style={{ width: 300 }} disabled />
                            </Form.Item>

                            <Form.Item
                                label="手机验证码"
                                name="code"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入正确的手机验证码!',
                                    },
                                ]}
                            >
                                <Row gutter={8}>
                                    <Col span={12}>
                                        {/* <Form.Item
                                                name="code"
                                                noStyle
                                                rules={[
                                                    {
                                                        required: true,
                                                        message: '请输入正确的手机验证码!',
                                                    },
                                                ]}
                                            > */}
                                        <Input />
                                        {/* </Form.Item> */}
                                    </Col>
                                    <Col span={12}>
                                        <Button style={{ width: '183px' }} disabled={second} onClick={verification}>{second ? `${second}s` : '获取验证码'}</Button>
                                    </Col>
                                </Row>
                            </Form.Item>
                        </div> :
                        <div>
                            <Form.Item
                                label="设置支付密码"
                                name="payPassWord"
                                rules={[
                                    { required: true, message: '请输入密码' },
                                    { pattern: /^\d{6,6}$/, message: '6位数字密码' }
                                ]}
                            >
                                <Input.Password autoComplete='new-password' />
                            </Form.Item>

                            <Form.Item
                                label="再次输入确认"
                                name="payPassWordTwo"
                                rules={[
                                    {
                                        required: true,
                                        message: '请再输入设置的支付密码!',
                                    },
                                    ({ getFieldValue }) => ({
                                        validator(rule, value) {
                                            if (!value || getFieldValue('payPassWord') === value) {
                                                return Promise.resolve();
                                            }
                                            return Promise.reject('两次输入密码不一致');
                                        },
                                    }),
                                ]}
                            >
                                <Input.Password autoComplete='new-password' />
                            </Form.Item>
                            <div style={{marginLeft: '22px', color: '#F39B29'}}>注：当设置新密码或者修改支付密码后，该支付密码将会同步至商城</div>
                        </div>
                    }
                </Form>
            </div>
            <CommonLoading loading={spinning} />
        </CommonModal >
    )
}